<template>
  <view>
    <view>
      <button @tap="chooseImg">上传图片</button>
      <image :src="img" />
    </view>
    <view>
      <button @tap="chooseVideo">上传视频</button>
      <video :src="video" />
    </view>
  </view>
</template>

<script setup>
import {ref} from 'vue';
import AliOSS from '@/utils/oss/oss';
import uniRequest from "@/utils/request";
import {onLoad} from '@dcloudio/uni-app';

const img = ref('');
const video = ref('');
const client = ref(null);

const initOss = async () => {
  const resp = await uniRequest.get('获取sts接口');
  client.value = new AliOSS({
    accessKeyId: resp.data.accessKeyId,
    accessKeySecret: resp.data.accessKeySecret,
    securityToken: resp.data.securityToken,
    expiration: resp.data.expiration
  });
}

onLoad(() => {
  initOss();
})

// 选择图片
const chooseImg = () => {
  uni.chooseImage({
    count: 1,
    success: async (file) => {
      const {success, data} = await client.value.ossUpload(file.tempFiles[0].path, file.tempFiles[0].name, 'img/')
      if (success) {
        img.value = data
      } else {
        uni.showToast({icon: 'none', title: data})
      }
    }
  })
}
// 选择视频
const chooseVideo = () => {
  uni.chooseVideo({
    count: 1,
    success: async (file) => {
      const {success, data} = await client.value.ossUpload(file.tempFilePath, file.name, 'video/')
      if (success) {
        video.value = data
      } else {
        uni.showToast({icon: 'none', title: data})
      }
    }
  })
}
</script>